package com.tanhua.server.controller;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author LiKe
 * @date 2022/1/19 21:59
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录-发送验证码
     * @param map
     * @return
     */

    @PostMapping("/login")
    public ResponseEntity sendCode(@RequestBody Map<String,String> map){
        //1.获取手机号
        String phone = map.get("phone");
        //2.调用业务层保存验证码
        userService.sendCode(phone);
        //3.返回数据
        //return ResponseEntity.status(500).body("出错了");
        return ResponseEntity.ok(null);
    }

    /**
     * 用户登录-登录验证
     * /user/loginVerification
     * phone 号码
     * verificationCode 验证码
     */
    @PostMapping("/loginVerification")
    public ResponseEntity login(@RequestBody Map<String,String> map){
        //1.接收手机号和验证码
        String phone = map.get("phone");
        String code = map.get("verificationCode");
        //2.调用登录业务方法
        Map retMap = userService.login(phone, code);

        return ResponseEntity.ok(retMap);
    }

    /**
     *  新用户首次登陆完善资料
     * @return
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo){
        //调用ThreadLocal获取用户id 填充UserInfo
        Long userId = UserHolder.getUserId();
        userInfo.setId(userId);
        //调用service
        userService.save(userInfo);
        return ResponseEntity.ok(null);
    }

    /**
     * 上传用户头像
     * @param headPhoto
     * @return
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto) throws IOException {
        //调用ThreadLocal获取用户id
        Long userId = UserHolder.getUserId();
        //调用service
        userService.updateHead(headPhoto,userId);

        return ResponseEntity.ok(null);
    }


}
